package com.heer.gymnasium.module.reservation.views;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import com.heer.amap.utils.ToastUtil;
import com.heer.gymnasium.R;
import com.heer.gymnasium.api.ResponseData.ApiResponse;
import com.heer.gymnasium.api.callback.BaseCallback;
import com.heer.gymnasium.base.BaseActivity;
import com.heer.gymnasium.constant.Type;
import com.heer.gymnasium.module.fellow.views.FellowDetailActivity;
import com.heer.gymnasium.module.fellow.views.InitiateFellowActivity;
import com.heer.gymnasium.module.fellow.views.InitiateMatchActivity;
import com.heer.gymnasium.module.order.beans.OrderResponseBean;
import com.heer.gymnasium.module.order.views.OrderActivity;
import com.heer.gymnasium.module.reservation.beans.ReservationBookItemResponseBean;
import com.heer.gymnasium.module.reservation.beans.ReservationGridBean;
import com.heer.gymnasium.module.reservation.beans.ReservationItemBean;
import com.heer.gymnasium.module.reservation.beans.ReservationItemResponseBean;
import com.heer.gymnasium.util.DialogUtils;
import com.heer.gymnasium.util.ScreenUtils;
import com.heer.gymnasium.util.StringUtils;
import com.heer.imagepick.DensityUtils;
import com.zhihuiyun.library.commonadapter.QuickTypeAdapter;
import com.zhihuiyun.library.commonadapter.ViewHolder;
import com.zhihuiyun.library.dialog.CommonDialog;
import com.zhihuiyun.library.view.MyGridView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnItemClick;
import butterknife.OnItemSelected;
import retrofit2.Call;
import retrofit2.Response;

import static com.heer.gymnasium.constant.Type.RESERVATION_TYPE_FELLOW;
import static com.heer.gymnasium.constant.Type.RESERVATION_TYPE_MATCH;
import static com.heer.gymnasium.constant.Type.RESERVATION_TYPE_NORMAL;

/**
 * Created by yan
 * on 2018/1/29
 * 订场
 */

public class ReservationActivity extends BaseActivity {
    private static final int LAYOUT = R.layout.layout_place;
    private static final int TIME_SPINNER_ID = R.id.layout_place_time_spinner;
    private static final int PLACE_GV_ID = R.id.layout_place_gv;
    private static final int TOTAL_ID = R.id.layout_place_total_tv;
    private static final int APPOINTMENT_ID = R.id.layout_place_appointment_tv;
    private static final int MATCH_ID = R.id.layout_place_match_tv;
    private static final int COLLECTIONS_ID = R.id.layout_place_collections_tv;
    private static final int BIND_AUTO_TV = R.id.layout_place_auto_tv;
    //
    private static final int ITEM = R.layout.item_reservation;
    private static final int ITEM_ROOT_ID = R.id.item_reservation_ll;
    private static final int ITEM_ICON_ID = R.id.item_reservation_icon_tv;
    private static final int ITEM_ICON_IV = R.id.item_reservation_icon_iv;
    private static final int ITEM_TV_ID = R.id.item_reservation_tv;
    private static final int ITEM_LINE_ID = R.id.item_reservation_line_v;
    private static final int ITEM_TIME_ID = R.id.item_reservation_time_tv;
    private static final int ITEM_TIME_ID_LINE = R.id.item_reservation_time_line_v;

    QuickTypeAdapter<ReservationGridBean> adapter;
    private List<ReservationGridBean> data;
    private List<Integer> states;//记录item状态，1,可选，2已售，3 拼单，4 约战，5 我的预定，
    private List<String> timeList;


    @BindView(PLACE_GV_ID)
    MyGridView gridView;
    @BindView(TIME_SPINNER_ID)
    Spinner spinner;
    @BindView(TOTAL_ID)
    TextView totalTextView;
    @BindView(BIND_AUTO_TV)
    TextView tvAutoReserve;
    @BindView(COLLECTIONS_ID)
    View btnFellow;
    @BindView(APPOINTMENT_ID)
    View btnNormal;
    @BindView(MATCH_ID)
    View btnMatch;

    private ReservationActivity $this;

    private String cateId;
    private int selectedPosition;
    private boolean isFirst = true;

    private float totalMoney = 0f;
    private int totalSize = 0;

    private int reservationType;//订场类型
    private final static int REQUEST_CODE_MATCH = 0x6;
    private final static int REQUEST_CODE_FELLOW = 0x16;

    private ArrayAdapter arrayAdapter;
    private boolean isAuto = false; //订单类型，默认为订多场  2:定多个场地,3:充值,4:购卡,5:私教，6:约战,7:拼单,8自动续订

    public static void startActivity(Activity activity, int pos, String cateId, int reservationType) {
        Intent intent = new Intent(activity, ReservationActivity.class);
        intent.putExtra(EXTRA_DATA, pos);
        intent.putExtra(EXTRA_ID, cateId);
        intent.putExtra(EXTRA_TYPE, reservationType);
        activity.startActivity(intent);
    }


    @Override
    protected void init() {
        super.init();
        $this = this;
        setContentView(LAYOUT);
        cateId = getIntent().getStringExtra(EXTRA_ID);
        selectedPosition = getIntent().getIntExtra(EXTRA_DATA, 0);
        reservationType = getIntent().getIntExtra(EXTRA_TYPE, RESERVATION_TYPE_NORMAL);
    }

    @Override
    protected void initView() {
        super.initView();
        switch (reservationType) {
            case RESERVATION_TYPE_NORMAL:
//                btnFellow.setVisibility(View.VISIBLE);
                btnNormal.setVisibility(View.VISIBLE);
//                btnMatch.setVisibility(View.VISIBLE);
                break;
            case Type.RESERVATION_TYPE_FELLOW:
                btnFellow.setVisibility(View.VISIBLE);
                btnNormal.setVisibility(View.GONE);
                btnMatch.setVisibility(View.GONE);
                tvAutoReserve.setVisibility(View.GONE);
                break;
            case Type.RESERVATION_TYPE_MATCH:
                btnFellow.setVisibility(View.GONE);
                btnNormal.setVisibility(View.GONE);
                btnMatch.setVisibility(View.VISIBLE);
                tvAutoReserve.setVisibility(View.GONE);
                break;
        }
        titleUtils.setTitleText("订场");
        titleUtils.startMainActivity(this);
        data = new ArrayList<>();
        timeList = new ArrayList<>();
        arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, timeList) {
            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                if (convertView == null) {
                    convertView = LayoutInflater.from(getContext()).inflate(android.R.layout.simple_list_item_1, null);
                    TextView tv = (TextView) convertView;
                    tv.setTextSize(16);
                }

                if (convertView instanceof TextView) {
                    TextView tv = (TextView) convertView;
                    tv.setText(timeList.get(position));
                }
                return convertView;
            }
        };
        arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(arrayAdapter);
        setTextView(totalTextView.getText().toString());
        adapter = new QuickTypeAdapter<ReservationGridBean>(this, data, ITEM) {
            @Override
            public void bindData4View(final ViewHolder holder, ReservationGridBean data, int type, final int pos) {
                boolean isPlace = TextUtils.equals(data.getKey(), ReservationGridBean.TYPE_FIELD);
                boolean isTime = TextUtils.equals(data.getKey(), ReservationGridBean.TYPE_TIME);
                if (isPlace || isTime) {
                    holder.setVisibility(ITEM_ROOT_ID, View.GONE);
                    holder.setVisibility(ITEM_TIME_ID, View.VISIBLE);
                    holder.setText(ITEM_TIME_ID, data.getText());
                    holder.setVisibility(ITEM_ICON_IV, View.GONE);
                    if (isTime) {
                        holder.setVisibility(ITEM_TIME_ID_LINE, View.VISIBLE);
                    }

                    if (isPlace || pos == 0) {
                        holder.setVisibility(ITEM_TIME_ID_LINE, View.GONE);
                    }
                } else {
                    holder.setVisibility(ITEM_ROOT_ID, View.VISIBLE);
                    holder.setVisibility(ITEM_TIME_ID, View.GONE);
                    holder.setVisibility(ITEM_TIME_ID_LINE, View.GONE);
                    holder.setTextColor(ITEM_TV_ID, Color.BLACK);
                    holder.setText(ITEM_TV_ID, data.getText());
                    holder.setVisibility(ITEM_ICON_IV, View.VISIBLE);
                    if (!TextUtils.isEmpty(data.getState())) {
                        if (TextUtils.equals(data.getState(), ReservationGridBean.STATUS_SOLD)) {
                            holder.setBg(ITEM_ROOT_ID, R.drawable.place_gray_bg);
                            holder.setBg(ITEM_LINE_ID, R.color.black);
                        } else if (TextUtils.equals(data.getState(), ReservationGridBean.STATUS_FELLOW) || TextUtils.equals(data.getState(), ReservationGridBean.STATUS_MATCH)) {
                            holder.setBg(ITEM_ROOT_ID, R.drawable.place_purple_bg);
                            holder.setBg(ITEM_LINE_ID, R.color.yellow);
                            holder.setTextColor(ITEM_TV_ID, Color.WHITE);
                            holder.setVisibility(ITEM_ICON_IV, View.GONE);
                            if (TextUtils.equals(data.getState(), ReservationGridBean.STATUS_FELLOW)) {
                                holder.setText(ITEM_ICON_ID, "拼");
                            } else {
                                holder.setText(ITEM_ICON_ID, "约");

                            }
                        } else if (TextUtils.equals(data.getState(), ReservationGridBean.STATUS_MINE)) {
                            holder.setBg(ITEM_ROOT_ID, R.drawable.place_orange_bg);
                            holder.setBg(ITEM_LINE_ID, R.color.black);
                        } else {
                            holder.setBg(ITEM_ROOT_ID, R.drawable.place_white_bg);
                            holder.setBg(ITEM_LINE_ID, R.color.yellow);

                        }
                    }
                }
                holder.setLis(ITEM_ROOT_ID, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        setState(pos, holder.getView(ITEM_ROOT_ID));
                        countTotal();
                    }
                });
            }
        };
        gridView.setAdapter(adapter);
        getTimeList();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isFirst) {
            getBookingList((String) spinner.getSelectedItem());
        }
    }

    @OnClick({APPOINTMENT_ID, COLLECTIONS_ID, MATCH_ID})
    public void onClick(View view) {
        switch (view.getId()) {
            case APPOINTMENT_ID:
                addOrder("", "", "", "", "", "", "");
                break;
            case COLLECTIONS_ID:
                if (totalSize > 0) {
                    InitiateFellowActivity.startActivity($this, REQUEST_CODE_FELLOW, totalMoney);
                } else {
                    ToastUtil.show($this, "请选择预定的场次");
                }
                break;
            case MATCH_ID:
                if (totalSize > 0) {
                    int money = (int) totalMoney / 2;
                    if ((int) totalMoney % 2 != 0) {
                        money++;
                    }
                    InitiateMatchActivity.startActivity($this, REQUEST_CODE_MATCH, money);
                } else {
                    ToastUtil.show($this, "请选择预定的场次");
                }
                break;
        }
    }

    @OnClick(BIND_AUTO_TV)
    public void onClickForAuto() {
        List<ReservationGridBean> newList = new ArrayList<>();
        for (ReservationGridBean item : data) {
            if (TextUtils.equals(ReservationGridBean.STATUS_MINE, item.getState())) {
                newList.add(item);
            }
        }

        if (newList.size() == 0) {
            ToastUtil.show($this, "请选择要预定的场地!");
            return;
        }

        DialogUtils.dialogForReservation(this, new DialogUtils.CallBackForReservation() {
            @Override
            public void callBack(View view, String num) {

                isAuto = true;
                if (!TextUtils.isEmpty(num.trim())) {
                    addOrder("", "", "", "", "", num, "");
                } else {
                    ToastUtil.show($this, "自动续订不可为空");
                }
            }
        });
    }

    @OnItemSelected(TIME_SPINNER_ID)
    public void onTimeListClicked(AdapterView<?> parent, View view, int position, long id) {
        isFirst = false;
        getBookingList(timeList.get(position));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_MATCH:
                    reservationType = RESERVATION_TYPE_MATCH;
                    String info = data.getStringExtra(EXTRA_DATA);
                    String tid = data.getStringExtra(EXTRA_ID);
                    String fight_show = data.getStringExtra(EXTRA_TYPE);
                    if (TextUtils.isEmpty(tid)) {
                        ToastUtil.show($this, "战队信息异常");
                    } else {
                        addOrder(tid, info, "", "", "", "", fight_show);
                    }
                    break;
                case REQUEST_CODE_FELLOW:
                    reservationType = RESERVATION_TYPE_FELLOW;
                    String infoFellow = data.getStringExtra(EXTRA_DATA);
                    String num = data.getStringExtra(EXTRA_ID);
                    String fight_show_fellow = data.getStringExtra(EXTRA_TYPE);
                    addOrder("", infoFellow, "", num, "", "", fight_show_fellow);
                    break;
            }
        }
    }

    //    获得时间列表
    private void getTimeList() {
        mAppHelper.apiService().getBookintTimeList(cateId).enqueue(new BaseCallback<ApiResponse<List<ReservationItemResponseBean>>>() {
            @Override
            public void onSuccess(Call<ApiResponse<List<ReservationItemResponseBean>>> call, Response<ApiResponse<List<ReservationItemResponseBean>>> response) {
                timeList.clear();
                timeList.addAll(ReservationItemBean.getStringList(response.body().getData()));
                arrayAdapter.notifyDataSetChanged();
                if (timeList.size() > selectedPosition) {
                    spinner.setSelection(selectedPosition, true);
                }
            }
        });
    }

    /**
     * 设置某些字体颜色
     */
    private void setTextView(String text) {
        SpannableString string = new SpannableString(text);
        string.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.yellow)), text.indexOf("择") + 1, text.indexOf("场"), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        totalTextView.setText(string);
    }

    private void getBookingList(String date) {
        mAppHelper.apiService().getBookingList(cateId, date).enqueue(new BaseCallback<ApiResponse<List<List<ReservationBookItemResponseBean>>>>() {
            @Override
            public void onSuccess(Call<ApiResponse<List<List<ReservationBookItemResponseBean>>>> call, Response<ApiResponse<List<List<ReservationBookItemResponseBean>>>> response) {
                if (response.body().getData() != null && response.body().getData().size() > 0) {
                    if (response.body().getData().get(0) != null) {
                        int column = response.body().getData().get(0).size();
                        gridView.setNumColumns(column);
                        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tvAutoReserve.getLayoutParams();
                        params.setMargins(DensityUtils.dip2px($this, -10 + (DensityUtils.px2dip($this, ScreenUtils.getScreenW()) - 30) * 1.0f / column), 0, 0, 0);
                    }
                }
                data.clear();
                data.addAll(ReservationGridBean.dataChange(response.body().getData()));
                adapter.notifyDataSetChanged();
            }
        });
    }

    /**
     * 设置状态
     *
     * @param pos
     * @param view
     */
    private void setState(int pos, View view) {
        final ReservationGridBean bean = data.get(pos);
        if (data.get(pos).getState().equals(ReservationGridBean.STATUS_EMPTY)) {
            view.setBackgroundResource(R.drawable.place_orange_bg);
            bean.setState(ReservationGridBean.STATUS_MINE);
            data.set(pos, bean);
            adapter.notifyDataSetChanged();
        } else if (data.get(pos).getState().equals(ReservationGridBean.STATUS_MINE)) {
            view.setBackgroundResource(R.drawable.place_white_bg);
            bean.setState(ReservationGridBean.STATUS_EMPTY);
            data.set(pos, bean);
            adapter.notifyDataSetChanged();
        } else if (data.get(pos).getState().equals(ReservationGridBean.STATUS_FELLOW)) {
            DialogUtils.showDialog($this, "", getResources().getString(R.string.fellow_content), "继续预定", "参与活动", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (view.getId() == CommonDialog.RES_ID_POSITIVE) {
                        getPlanOrder(bean, "参与活动");
                    } else {
                        getPlanOrder(bean, "继续预定");
                    }
                }
            });
        } else if (data.get(pos).getState().equals(ReservationGridBean.STATUS_MATCH)) {

            DialogUtils.showDialog($this, "", getResources().getString(R.string.match_content), "继续预定", "应战", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (view.getId() == CommonDialog.RES_ID_POSITIVE) {
                        getPlanOrder(bean, "应战");
                    } else {
                        getPlanOrder(bean, "继续预定");
                    }
                }
            });
        }
    }

    /**
     * 计算总额
     */
    private void countTotal() {
        totalSize = 0;
        totalMoney = 0;
        for (ReservationGridBean item : data) {
            if (TextUtils.equals(ReservationGridBean.STATUS_MINE, item.getState())) {
                totalSize++;
                totalMoney += StringUtils.toFloat(item.getText());
            }
        }
        totalTextView.setText(String.format("已选择%d场，共计¥%.2f", totalSize, totalMoney));
    }

    private void getPlanOrder(final ReservationGridBean bean, final String type) {
        mAppHelper.apiService().getPlanOrder(bean.getId(), bean.getStartTime(), bean.getEndTime()).enqueue(new BaseCallback<ApiResponse<Object>>() {
            @Override
            public void onSuccess(Call<ApiResponse<Object>> call, Response<ApiResponse<Object>> response) {
                if (response.body().getData() == null) {
                    return;
                }
                String orderId = ((LinkedTreeMap) response.body().getData()).get("order_id") + "";
                orderId = orderId.substring(0, orderId.lastIndexOf("."));
                if (type.equals("参与活动")) {
                    FellowDetailActivity.startActivity($this, Type.TYPE_FELLOW, orderId);
                } else if (type.equals("应战")) {
                    FellowDetailActivity.startActivity($this, Type.TYPE_MATCH, orderId);
                } else {
                    addOrder(bean);
                }
            }
        });
    }


    private void addOrder(String corps_id, String info, String order_id, String order_num, String category_id, String num, String fight_show) {
        String orderType = "";
        String place_id = "",
                start_time = "",
                end_time = "",
                plan_info = "",
                card_id = "",
                coach_id = "";
        List<ReservationGridBean> newList = new ArrayList<>();
        for (ReservationGridBean item : data) {
            if (TextUtils.equals(ReservationGridBean.STATUS_MINE, item.getState())) {
                newList.add(item);
            }
        }

        if (newList.size() == 0) {
            ToastUtil.show($this, "请选择要预定的场地!");
            return;
        }

        plan_info = new Gson().toJson(ReservationBookItemResponseBean.dataChange(newList));
        if (reservationType == RESERVATION_TYPE_NORMAL) {
            orderType = Type.ORDER_MORE_STDIUM;
        } else if (reservationType == RESERVATION_TYPE_MATCH) {
            orderType = Type.ORDER_YUE;
        } else if (reservationType == RESERVATION_TYPE_FELLOW) {
            orderType = Type.ORDER_FELLOW;
            category_id = newList.get(0).getCategoryId();
        }
        if (isAuto) {
            orderType = Type.ORDER_AUTO;
        }

        final String finalOrderType = orderType;
        mAppHelper.apiService().addOrder(orderType,
                place_id,
                start_time,
                end_time,
                plan_info,
                card_id,
                coach_id,
                num,
                corps_id,
                order_id,
                order_num,
                info,
                category_id,
                fight_show).enqueue(new BaseCallback<ApiResponse<OrderResponseBean>>() {
            @Override
            public void onSuccess(Call<ApiResponse<OrderResponseBean>> call, Response<ApiResponse<OrderResponseBean>> response) {
                if (finalOrderType.equals(Type.ORDER_MORE_STDIUM) || finalOrderType.equals(Type.ORDER_ONE_STDIUM)) {
                    OrderActivity.startActivity($this, OrderActivity.OrderType.from_coupon, response.body().getData().getOrder_id(), finalOrderType, true);
                } else
                    OrderActivity.startActivity($this, OrderActivity.OrderType.from_coupon, response.body().getData().getOrder_id(), finalOrderType);
            }

        });
    }

    private void addOrder(ReservationGridBean bean) {
        String orderType = "";
        String place_id = "",
                start_time = "",
                end_time = "",
                plan_info = "",
                card_id = "",
                coach_id = "",
                num = "",
                corps_id = "",
                order_id = "",
                order_num = "",
                info = "",
                category_id = "",
                fight_show = "";
        List<ReservationGridBean> newList = new ArrayList<>();
        newList.add(bean);


        plan_info = new Gson().toJson(ReservationBookItemResponseBean.dataChange(newList));
        orderType = Type.ORDER_MORE_STDIUM;
        if (isAuto) {
            orderType = Type.ORDER_AUTO;
        }

        final String finalOrderType = orderType;
        mAppHelper.apiService().addOrder(orderType,
                place_id,
                start_time,
                end_time,
                plan_info,
                card_id,
                coach_id,
                num,
                corps_id,
                order_id,
                order_num,
                info,
                category_id,
                fight_show).enqueue(new BaseCallback<ApiResponse<OrderResponseBean>>() {
            @Override
            public void onSuccess(Call<ApiResponse<OrderResponseBean>> call, Response<ApiResponse<OrderResponseBean>> response) {
                OrderActivity.startActivity($this, OrderActivity.OrderType.from_coupon, response.body().getData().getOrder_id(), finalOrderType, true);
            }

        });
    }
}
